package com.kma.summer2012.client.presenters.request;


import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import com.kma.summer2012.client.CrumbsEventBus;
import com.kma.summer2012.client.constants.ConstantsHolder;
import com.kma.summer2012.client.constants.ConstantsPresenter;
import com.kma.summer2012.client.events.engineer.CloseRequestEvent;
import com.kma.summer2012.client.events.manager.AssignForManagerEvent;
import com.kma.summer2012.client.events.reject.RejectRequestEvent;
import com.kma.summer2012.client.events.request.ExportRequestEvent;
import com.kma.summer2012.client.events.request.MainPageEvent;
import com.kma.summer2012.client.presenters.Presenter;
import com.kma.summer2012.client.presenters.header.HeaderPresenter;
import com.kma.summer2012.client.presenters.manager.WorksCatalogPresenter;
import com.kma.summer2012.client.services.AbstractCallBack;
import com.kma.summer2012.client.services.request.CrumbsRequestService;
import com.kma.summer2012.client.services.session.CrumbsSessionService;
import com.kma.summer2012.client.services.user.CrumbsUserService;
import com.kma.summer2012.client.styles.style2.Recources;
import com.kma.summer2012.client.view.manager.WorksCatalogView;
import com.kma.summer2012.shared.model.*;
import com.smartgwt.client.widgets.grid.ListGridRecord;

import java.util.*;

//import com.kma.summer2012.client.events.operator.OperatorShowRequestEvent;

public class RequestPresenter implements Presenter {

    public interface Display {
        public Map<Integer, Integer> getAmountsOfWorkValues();

        public HasText getDateOfCreation();

        public HasText getState();

        public int getId();

        public void makeSaveButtonDisabled();

        public Integer getTotalSumOfWork();

        public String getRequestInfo();

        public Integer getTimeRequired();

        public HasValue<String> getClAddress();

        public String getStartTime();

        public String getEndTime();

        public String getDateValue();

        public Integer getActualTimeOfWork();

        //public HasValue getCalendar();
        public String getTextDate();

        public HasValue<String> getClName();

        public HasValue<String> getClMail();

        public HasValue<String> getComments();

        public HasClickHandlers getCatalog();

        public HasClickHandlers getSendForProcessing();

        public Map<Integer, UICrumbsWorkItem> getWorkList();

        public Map<Integer, TextBox> getAmountOfWorkInTxtBox();

        HasClickHandlers getSaveRequestButton();

        HasClickHandlers getOperatorEditRequestButton();

        HasClickHandlers getManagerEditRequestButton();

        /*HasClickHandlers getDeleteButton(); */
        HasClickHandlers getDeleteCloseButton();

        HasClickHandlers getRejectButton();

        HasClickHandlers getCancelButton();

        HasClickHandlers getBackButton();

        HasClickHandlers getCloseButton();

        HasClickHandlers getExportButton();

        HasClickHandlers getAssignButton();

        Widget asWidget();


        public void setParametres(UICrumbsRequest o);

        public void setTotalSumOfWork(Integer o);

        Boolean validateRequestInfo();

        Boolean validateClientInfo();

        public void updateWorkField();

    }

    private final Display display;
    private UICrumbsRequest request;
    private UICrumbsUser user;
    public static ConstantsPresenter constants = GWT.create(ConstantsPresenter.class);


    public RequestPresenter(Display display) {
        this.display = display;
        bind();
        CrumbsSessionService.App.getInstance().getParameterRequest("currentRequest", new AbstractCallBack<UICrumbsRequest>() {
            @Override
            public void onSuccess(UICrumbsRequest uiCrumbsRequest) {


                try {
                    if (uiCrumbsRequest != null) {
                        if (uiCrumbsRequest.getState().equals(constants.rejectedState())) {
                            CrumbsRequestService.App.getInstance().getLastCommentFromManger(uiCrumbsRequest, new AbstractCallBack<UICrumbsRequest>() {
                                @Override
                                public void onSuccess(UICrumbsRequest uiCrumbsRequest) {

                                    RequestPresenter.this.display.setParametres(uiCrumbsRequest);
                                    request = uiCrumbsRequest;

                                }
                            });
                        } else {
                            RequestPresenter.this.display.setParametres(uiCrumbsRequest);
                            request = uiCrumbsRequest;

                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        );


    }

    public RequestPresenter(Display display, Boolean bool) {

        this.display = display;
        bind();
        CrumbsSessionService.App.getInstance().getParameterRequest("currentRequest", new AbstractCallBack<UICrumbsRequest>() {
            @Override
            public void onSuccess(UICrumbsRequest uiCrumbsRequest) {

                CrumbsRequestService.App.getInstance().initialize(uiCrumbsRequest, new AbstractCallBack<UICrumbsRequest>() {
                    @Override
                    public void onSuccess(UICrumbsRequest result) {
                        RequestPresenter.this.display.setParametres(result);
                        request = result;

                    }

                });
            }
        });
    }


    private void bind() {
        this.display.getCatalog().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                RequestPresenter.this.display.updateWorkField();
                final DialogBox dialogBox = createDialogBox();
                dialogBox.setGlassEnabled(true);
                dialogBox.setAnimationEnabled(true);

                // Create a button to show the dialog Box

                dialogBox.center();
                dialogBox.show();

            }
        });
        this.display.getSaveRequestButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                RequestPresenter.this.display.updateWorkField();
                if (RequestPresenter.this.display.validateRequestInfo()) {

                    if (RequestPresenter.this.display.validateClientInfo()) {
                        RequestPresenter.this.display.makeSaveButtonDisabled();
                        doSave();
                    } else Window.alert("Not all necessary information about client");
                }
                {
                }// else Window.alert("Not all necessary information about mainPage");
            }
        });
        this.display.getManagerEditRequestButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                if (RequestPresenter.this.display.validateRequestInfo()) {

                    if (RequestPresenter.this.display.validateClientInfo()) {
                        doEditManager();
                    } else Window.alert("Not all necessary information about client");
                }
                {
                }// else Window.alert("Not all necessary information about mainPage");
            }
        });
        this.display.getOperatorEditRequestButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                if (RequestPresenter.this.display.validateRequestInfo()) {

                    if (RequestPresenter.this.display.validateClientInfo()) {
                        doEditOperator();
                    } else Window.alert("Not all necessary information about client");
                }// else Window.alert("Not all necessary information about mainPage");
            }
        });
        this.display.getCancelButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doCancel();
            }
        });
        this.display.getRejectButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doReject();
            }
        });

        this.display.getSendForProcessing().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                RequestPresenter.this.display.updateWorkField();
                doSendForProcessing();
            }
        });
        this.display.getAssignButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doAssign();
            }
        });
        this.display.getBackButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                //saveComment();
                CrumbsEventBus.getInstance().fireEvent(new MainPageEvent());


            }
        });
        this.display.getCloseButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                CrumbsEventBus.getInstance().fireEvent(new CloseRequestEvent(request));

            }
        });
        this.display.getDeleteCloseButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                doDelete();

            }
        });

        this.display.getExportButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doExport();
            }
        });
    }

    @Override
    public void go(HasWidgets container) {
        container.clear();
        container.add(display.asWidget());
    }

    private void doExport() {
        List<UICrumbsRequest> list = new ArrayList<UICrumbsRequest>();
        list.add(this.request);
        CrumbsEventBus.getInstance().fireEvent(new ExportRequestEvent(list));
    }

    public void doAssign() {
        if (!RequestPresenter.this.display.getComments().getValue().equals("")) {
            saveComment();
        }
        CrumbsEventBus.getInstance().fireEvent(new AssignForManagerEvent(RequestPresenter.this.display.getId()));
    }

    public void doDelete() {
        /*List<UICrumbsRequest> uiCrumbsRequestList=new ArrayList<UICrumbsRequest>();
        for (int i = 0; i < this.currentRequests.size(); i++)
            uiCrumbsRequestList.add(this.currentRequests.get(i));
         */

        List<Integer> requestIdList = new ArrayList<Integer>();

        requestIdList.add(request.getId());

        CrumbsRequestService.App.getInstance().deleteRequests(requestIdList, new AbstractCallBack<Boolean>() {
            @Override
            public void onSuccess(Boolean boo) {
                Window.alert("The request was deleted");
                CrumbsEventBus.getInstance().fireEvent(new MainPageEvent());
            }
        });


    }

    public void doReject() {
        CrumbsRequestService.App.getInstance().getById(this.display.getId(), new AbstractCallBack<UICrumbsRequest>() {
            @Override
            public void onSuccess(UICrumbsRequest uiCrumbsRequest) {
                CrumbsEventBus.getInstance().fireEvent(new RejectRequestEvent(uiCrumbsRequest));
            }
        });
        /*if (RequestPresenter.this.display.getComments().equals("")) {
            Window.alert("You must write the reason of rejection");

            CrumbsUserService.App.getInstance().checkLogin(new AsyncCallback<UICrumbsUser>() {
                @Override
                public void onFailure(Throwable caught) {
                    Window.alert("Error with authorization");
                }

                @Override
                public void onSuccess(UICrumbsUser result) {
                    int requestId = RequestPresenter.this.display.getId();
                    CrumbsRequestService.App.getInstance().sendForProcessing(result.getUserId(), requestId, new AsyncCallback<Boolean>() {
                        @Override
                        public void onFailure(Throwable caught) {
                            // throw new Exception("Error in sending for processing", caught);
                        }

                        @Override
                        public void onSuccess(Boolean result) {
                            if (result == true) Window.alert("WAS SENT FOR PROCESSING");
                            else Window.alert("WAS NOT SENT ");
                            CrumbsEventBus.getInstance().fireEvent(new MainPageEvent());
                        }
                    });

                }
            });
        } else {
            //CrumbsRequestService.App.getInstance().makeReject(comment, new AsyncCallback<Boolean>() {

        }     */
    }

    public void saveComment() {
        UICrumbsUser u = new UICrumbsUser();
        CrumbsUserService.App.getInstance().checkLogin(new AsyncCallback<UICrumbsUser>() {
            @Override
            public void onFailure(Throwable caught) {
                Window.alert("Error with authorization");
            }

            @Override
            public void onSuccess(UICrumbsUser currentUser) {
                currentUser = HeaderPresenter.getUser();
                if (RequestPresenter.this.display.getComments() != null || !RequestPresenter.this.display.getComments().equals("")) {
                    UIComment comment = new UIComment();

                    comment.setCommenter(HeaderPresenter.getUser());
                    comment.setrequestId(RequestPresenter.this.display.getId());
                    comment.setComment(RequestPresenter.this.display.getComments().getValue());
                    DateTimeFormat fmt = DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_SERVER());
                    Date date = new Date();

                    comment.setCommentDate(fmt.format(date));

                    CrumbsRequestService.App.getInstance().saveComments(comment, new AsyncCallback<Boolean>() {


                        @Override
                        public void onFailure(Throwable throwable) {
                            Window.alert("Request wasn't updated");
                        }

                        @Override
                        public void onSuccess(Boolean result) {
                            if (result == true) Window.alert("Comment was saved");
                            else Window.alert("Comment was NOT saved");
                        }
                    });

                }
            }
        });
    }

    public void doSendForProcessing() {
        if (RequestPresenter.this.display.getComments() != null && !RequestPresenter.this.display.getComments().getValue().equals("")) {
            this.saveComment();
        }
        /*CrumbsUserService.App.getInstance().checkLogin(new AsyncCallback<UICrumbsUser>() {
            @Override
            public void onFailure(Throwable caught) {
                Window.alert("Error with authorization");
            }

            @Override
            public void onSuccess(UICrumbsUser result) {*/
        UICrumbsUser result = HeaderPresenter.getUser();
        int requestId = RequestPresenter.this.display.getId();
        CrumbsRequestService.App.getInstance().sendForProcessing(result.getUserId(), requestId, new AsyncCallback<Boolean>() {
            @Override
            public void onFailure(Throwable caught) {
                // throw new Exception("Error in sending for processing", caught);
            }

            @Override
            public void onSuccess(Boolean result) {
                if (result == true) Window.alert("WAS SENT FOR PROCESSING");
                else Window.alert("WAS NOT SENT ");
                CrumbsEventBus.getInstance().fireEvent(new MainPageEvent());
            }
        });

    }


    public void doCancel() {
        CrumbsEventBus.getInstance().fireEvent(new MainPageEvent());

    }


    public void doSave() {

        UICrumbsClient newClient = new UICrumbsClient();
        newClient.setAdress(RequestPresenter.this.display.getClAddress().getValue());
        newClient.setMail(RequestPresenter.this.display.getClMail().getValue());
        newClient.setName(RequestPresenter.this.display.getClName().getValue());

        CrumbsRequestService.App.getInstance().addNewClient(newClient, new AsyncCallback<UICrumbsClient>() {

            @Override
            public void onFailure(Throwable throwable) {
            }

            @Override
            public void onSuccess(UICrumbsClient client) {

                UICrumbsRequest newRequest = new UICrumbsRequest();
                newRequest.setUicrumbsClient(client);


                newRequest.setState(RequestPresenter.this.display.getState().getText());
                newRequest.setDateOfCreation(RequestPresenter.this.display.getDateOfCreation().getText());

                if (RequestPresenter.this.display.getRequestInfo() != null)
                    newRequest.setRequestInfo(RequestPresenter.this.display.getRequestInfo());
                else
                    newRequest.setRequestInfo("");

                Map<UICrumbsWorkItem, Short> work = new HashMap<UICrumbsWorkItem, Short>();
                for (Integer key : RequestPresenter.this.display.getWorkList().keySet()) {
                    try {
                        Integer nmb = Integer.parseInt(RequestPresenter.this.display.getAmountOfWorkInTxtBox().get(RequestPresenter.this.display.getWorkList().get(key).getId()).getValue());

                        RequestPresenter.this.display.getAmountsOfWorkValues().put(key, nmb);
                        work.put(RequestPresenter.this.display.getWorkList().get(key), nmb.shortValue());

                    } catch (NumberFormatException e) {
                        short i = 1;
                        work.put(RequestPresenter.this.display.getWorkList().get(key), i);

                        Window.alert("NOT CORRECT NUMBER FOR AMOUNT OF WORK");
                    }

                }
                newRequest.setUicrumbsWorkItems(work);


                CrumbsRequestService.App.getInstance().addNewRequest(newRequest, new AsyncCallback<UICrumbsRequest>() {

                    @Override
                    public void onFailure(Throwable throwable) {
                        Window.alert("Request wasn't added");
                    }

                    @Override
                    public void onSuccess(final UICrumbsRequest uiCrumbsRequest) {

                        int start = DateTimeFormat.getFormat("HH:mm").parse(display.getStartTime().toString()).getHours();
                        int end = DateTimeFormat.getFormat("HH:mm").parse(display.getEndTime().toString()).getHours();
                        String day = RequestPresenter.this.display.getDateValue();

                        String startDate = day.concat(" " + display.getStartTime().concat(":00").toString());
                        String endDate = day.concat(" " + display.getEndTime().concat(":00").toString());
                        final Date stDate = DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_FULL()).parse(startDate);
                        final Date ndDate = DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_FULL()).parse(endDate);


                        CrumbsRequestService.App.getInstance().saveDate(uiCrumbsRequest.getId(), stDate, ndDate, new AsyncCallback<Integer>() {
                            @Override
                            public void onFailure(Throwable caught) {


                            }

                            @Override
                            public void onSuccess(Integer result) {
                                UIComment comment = new UIComment();
                                comment.setCommenter(HeaderPresenter.getUser());
                                comment.setrequestId(uiCrumbsRequest.getId());
                                DateTimeFormat fmt = DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_SERVER());
                                Date date = new Date();
                                comment.setComment("");
                                comment.setCommentDate(fmt.format(date));
                                CrumbsRequestService.App.getInstance().saveComments(comment, new AsyncCallback<Boolean>() {
                                    @Override
                                    public void onFailure(Throwable throwable) {


                                        //To change body of implemented methods use File | Settings | File Templates.
                                    }

                                    @Override
                                    public void onSuccess(Boolean aBoolean) {
                                        CrumbsEventBus.getInstance().fireEvent(new MainPageEvent());
                                    }
                                });


                            }
                        });
                    }

                });
            }
        });
    }


    public void doEditManager() {
        if (RequestPresenter.this.display.getComments() != null || !RequestPresenter.this.display.getComments().equals("")) {
            this.saveComment();
        }
        CrumbsRequestService.App.getInstance().editManagerRequest(this.display.getId(), new AsyncCallback<Boolean>() {
            @Override
            public void onFailure(Throwable throwable) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void onSuccess(Boolean aBoolean) {
                if (RequestPresenter.this.display.getState().toString() != constants.needMoreInfoState()) {
                    CrumbsEventBus.getInstance().fireEvent(new MainPageEvent());
                }
            }
        });

    }

    public void doEditOperator() {


        CrumbsRequestService.App.getInstance().getById(this.display.getId(), new AsyncCallback<UICrumbsRequest>() {
            @Override
            public void onFailure(Throwable throwable) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void onSuccess(UICrumbsRequest uiCrumbsRequest) {
                //To change body of implemented methods use File | Settings | File Templates.

                // UICrumbsRequest request = new UICrumbsRequest();
                // request.setUicrumbsClient(newClient);

                //request.setId(RequestPresenter.this.display.getId());
                UICrumbsClient newClient = new UICrumbsClient();
                newClient.setId(uiCrumbsRequest.getUicrumbsClient().getId());
                newClient.setAdress(RequestPresenter.this.display.getClAddress().getValue());
                newClient.setMail(RequestPresenter.this.display.getClMail().getValue());
                newClient.setName(RequestPresenter.this.display.getClName().getValue());

                uiCrumbsRequest.getUicrumbsClient().setAdress(RequestPresenter.this.display.getClAddress().getValue());
                uiCrumbsRequest.getUicrumbsClient().setMail(RequestPresenter.this.display.getClMail().getValue());
                uiCrumbsRequest.getUicrumbsClient().setName(RequestPresenter.this.display.getClName().getValue());
                uiCrumbsRequest.setState(RequestPresenter.this.display.getState().getText());
                uiCrumbsRequest.setDateOfCreation(RequestPresenter.this.display.getDateOfCreation().getText());

                if (RequestPresenter.this.display.getRequestInfo().toString() != null)
                    uiCrumbsRequest.setRequestInfo(RequestPresenter.this.display.getRequestInfo().toString());

                // if (RequestPresenter.this.display.getActualTimeOfWork() != null)
                //  uiCrumbsRequest.setActualTimeOfWork(RequestPresenter.this.display.getActualTimeOfWork());

                if (RequestPresenter.this.display.getComments() != null && !RequestPresenter.this.display.getComments().getValue().equals("") &&
                        RequestPresenter.this.display.getState().equals("Rejected")) {
                    RequestPresenter.this.saveComment();
                }
                //??????????????????????????????????????????
                if (RequestPresenter.this.display.getWorkList().size() > 0) {
                    Map<UICrumbsWorkItem, Short> work = new HashMap<UICrumbsWorkItem, Short>();
                    for (Integer key : RequestPresenter.this.display.getWorkList().keySet()) {
                        try {
                            Integer nmb = Integer.parseInt(RequestPresenter.this.display.getAmountOfWorkInTxtBox().get(RequestPresenter.this.display.getWorkList().get(key).getId()).getValue());
                            RequestPresenter.this.display.getAmountsOfWorkValues().put(key, nmb);
                            work.put(RequestPresenter.this.display.getWorkList().get(key), nmb.shortValue());

                        } catch (NumberFormatException e) {
                            short i = 1;
                            work.put(RequestPresenter.this.display.getWorkList().get(key), i);

                            Window.alert("NOT CORRECT NUMBER FOR AMOUNT OF WORK");
                        }
                        /*  Integer nmb = Integer.parseInt(RequestPresenter.this.display.getAmounts().get(RequestPresenter.this.display.getWorkList().get(key).getId()).getValue());

                  RequestPresenter.this.display.getWorkList().get(key).setAmount(nmb);
                  work.put(nmb.shortValue(), RequestPresenter.this.display.getWorkList().get(key));     */

                    }
                    uiCrumbsRequest.setUicrumbsWorkItems(work);
                }

                CrumbsRequestService.App.getInstance().updateClient(newClient, new AsyncCallback<UICrumbsClient>() {


                    @Override
                    public void onFailure(Throwable throwable) {
                        Window.alert("client wasn't updated");
                    }

                    @Override
                    public void onSuccess(UICrumbsClient client) {
                        //   Window.alert("Information was updated");
                    }
                });
                CrumbsRequestService.App.getInstance().editOperatorRequest(uiCrumbsRequest, new AsyncCallback<UICrumbsRequest>() {


                    @Override
                    public void onFailure(Throwable throwable) {
                        Window.alert("Request wasn't updated");
                    }

                    @Override
                    public void onSuccess(UICrumbsRequest request) {

                        //  Window.alert("Request was updated " + request.getRequestInfo() + " " + request.getState() + " " + request.getDateOfCreation() + " " + request.getId());
                        int start = DateTimeFormat.getFormat("HH:mm").parse(display.getStartTime().toString()).getHours();
                        int end = DateTimeFormat.getFormat("HH:mm").parse(display.getEndTime().toString()).getHours();
                        String day = RequestPresenter.this.display.getDateValue();

                        String startDate = day.concat(" " + display.getStartTime().concat(":00").toString());
                        String endDate = day.concat(" " + display.getEndTime().concat(":00").toString());
                        final Date stDate = DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_FULL()).parse(startDate);
                        final Date ndDate = DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_FULL()).parse(endDate);
                        CrumbsRequestService.App.getInstance().updateDate(request.getId(), stDate, ndDate, new AsyncCallback<Integer>() {

                            @Override
                            public void onFailure(Throwable caught) {
                            }

                            @Override
                            public void onSuccess(Integer result) {
                                CrumbsEventBus.getInstance().fireEvent(new MainPageEvent());


                            }
                        });

                    }
                });
            }
        });

    }

    private DialogBox createDialogBox() {
        // Create a dialog box and set the caption text
        final DialogBox dialogBox = new DialogBox();

        dialogBox.ensureDebugId("cwDialogBox");
        dialogBox.setText("Catalog ");

        // Create a table to layout the content
        VerticalPanel dialogContents = new VerticalPanel();
        dialogContents.setSpacing(4);
        dialogBox.setWidget(dialogContents);

        // Add some text to the top of the dialog
        WorksCatalogView showCatalog = new WorksCatalogView();
        final WorksCatalogPresenter showCatalogPresenter = new WorksCatalogPresenter(showCatalog);

        HTML details = new HTML("DETAILES");
        dialogContents.add(showCatalog);
        dialogContents.setCellHorizontalAlignment(
                details, HasHorizontalAlignment.ALIGN_CENTER);

        Button addButton = new Button(
                "Add ", new ClickHandler() {
            public void onClick(ClickEvent event) {
                List<UICrumbsWorkItem> itemList = new ArrayList<UICrumbsWorkItem>();
                ListGridRecord[] records = showCatalogPresenter.getDisplay().getTreeGrid().getSelectedRecords();
                //String temp = "";
                for (ListGridRecord record : records) {
                    UICrumbsWorkItem item = new UICrumbsWorkItem();
                    item.setParent(record.getAttributeAsBoolean("IsParent"));
                    if (record.getAttribute("ReportsTo") == null) {
                        item.setParentId(0);
                    } else {
                        item.setParentId(record.getAttributeAsInt("ReportsTo"));
                    }
                    item.setId(record.getAttributeAsInt("Id"));
                    if (item.isParent() == false) {
                        item.setRuntime(record.getAttributeAsInt("RunTime"));
                    }
                    item.setWorkDescription(record.getAttribute("WorkDescription"));
                    item.setWorkName(record.getAttribute("Work"));
                    if (item.isParent() == false) {
                        itemList.add(item);
                    }
                    // temp+=record.getAttribute("IsParent")+"; ";

                }
                //Window.alert("Your works was successfully added!");
                Integer currentSum = RequestPresenter.this.display.getTotalSumOfWork();

                for (UICrumbsWorkItem workItem : itemList) {

                    if (RequestPresenter.this.display.getWorkList().containsKey(workItem.getId())) {

                        Integer count = RequestPresenter.this.display.getAmountsOfWorkValues().get(workItem.getId());
                        count++;

                        RequestPresenter.this.display.getAmountsOfWorkValues().put(workItem.getId(), count);

                        currentSum += RequestPresenter.this.display.getAmountsOfWorkValues().get(workItem.getId()) * RequestPresenter.this.display.getWorkList().get(workItem.getId()).getRuntime();

                    } else {

                        RequestPresenter.this.display.getAmountsOfWorkValues().put(workItem.getId(), 1);

                        RequestPresenter.this.display.getWorkList().put(workItem.getId(), workItem);


                        currentSum += RequestPresenter.this.display.getAmountsOfWorkValues().get(workItem.getId()) * workItem.getRuntime();

                    }

                }
                RequestPresenter.this.display.setTotalSumOfWork(currentSum);
                RequestPresenter.this.display.updateWorkField();
                dialogBox.hide();
            }
        });
        Button cancelButton = new Button("Cancel", new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                dialogBox.hide();
            }
        });
        addButton.addStyleName(Recources.INSTANCE.styles().Caption());
        cancelButton.addStyleName(Recources.INSTANCE.styles().Caption());
        dialogContents.add(addButton);
        dialogContents.add(cancelButton);
        if (LocaleInfo.getCurrentLocale().isRTL()) {
            dialogContents.setCellHorizontalAlignment(
                    addButton, HasHorizontalAlignment.ALIGN_LEFT);
            dialogContents.setCellHorizontalAlignment(
                    cancelButton, HasHorizontalAlignment.ALIGN_LEFT);

        } else {
            dialogContents.setCellHorizontalAlignment(
                    cancelButton, HasHorizontalAlignment.ALIGN_RIGHT);
            dialogContents.setCellHorizontalAlignment(
                    addButton, HasHorizontalAlignment.ALIGN_RIGHT);
        }

        // Return the dialog box
        return dialogBox;
    }
}

